﻿using MaiPlanServer.IRepository;
using MaiPlanServer.IServices.IQualityServices;
using MaiPlanServer.Model;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

namespace MaiPlanServer.Services.QualityServices
{
    public class DefectServices : IDefectServices
    {
        public DefectServices(IBaseRepository baseConn)
        {
            BaseConn = baseConn;
        }

        public IBaseRepository BaseConn { get; }

        public async Task<bool> AddAsync(qc_defect model)
        {
            var result = await BaseConn.InsertAsync(model);
            return result;
        }

        public async Task<bool> DelAsync(string Id)
        {
            var result=await BaseConn.DeleteAsync("delete dbo.qc_defect where defect_id=@Id", new {Id });
            return result;
        }

        public async Task<bool> DelAsync(string[] Id)
        {
            var result = await BaseConn.DeleteAsync("delete dbo.qc_defect where defect_id in @Id", new {Id});
            return result;
        }

        public async Task<int> GetCountAsync(string Describe, string Type, string Level)
        {
            string sql = "select count(1) from dbo.qc_defect where defect_describe like @Describe";
            if (!string.IsNullOrEmpty(Type))
            {
                sql += " and index_type=@Type";
            }
            if (!string.IsNullOrEmpty(Level))
            {
                sql += " and defect_level=@Level";
            }
            var result = await BaseConn.GetRecoreCountAsync(sql, new { Describe = "%"+ Describe + "%",Type=Type,Level=Level });
            return result;
        }

        public async Task<IEnumerable<qc_defect>> GetJsonAsync(int PageIndex, int PageSize, string Describe, string Type, string Level)
        {
            string sql = "select * from dbo.qc_defect where defect_describe like @Describe";
            if (!string.IsNullOrEmpty(Type))
            {
                sql += " and index_type=@Type";
            }
            if (!string.IsNullOrEmpty(Level))
            {
                sql += " and defect_level=@Level";
            }
            sql += " order by create_time desc offset @PageSize*(@PageIndex-1) rows fetch next @PageSize row only";
            var result = await BaseConn.QueryAsync<qc_defect>(sql, new { PageIndex= PageIndex, PageSize= PageSize, Describe="%"+ Describe + "%", Type= Type, Level= Level });
            return result;
        }

        public async Task<bool> UpdateAsync(qc_defect model)
        {
            var result=await BaseConn.UpdateAsync(model,"defect_id");
            return result;
        }
    }
}
